package com.ehsunbehravesh.varzesh3.gui;

import com.ehsunbehravesh.Utils;
import com.ehsunbehravesh.utils.update.Updater;
import com.ehsunbehravesh.varzesh3.gui.resource.RL;
import com.ehsunbehravesh.varzesh3.net.Newspaper;
import com.ehsunbehravesh.varzesh3.net.NewspaperFetch;
import com.ehsunbehravesh.varzesh3.net.Ranking;
import com.ehsunbehravesh.varzesh3.net.RankingFetch;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.ComponentOrientation;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.HeadlessException;
import java.awt.Image;
import java.awt.Toolkit;
import java.io.File;
import java.net.MalformedURLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Observable;
import java.util.Observer;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTabbedPane;
import javax.swing.JTable;
import javax.swing.UIManager;

public class MainFrame extends JFrame
        implements Observer {

  private List<Newspaper> newspapers;
  private NewspaperFetch fetcher;
  private JPanel pnlMain;
  private JLabel lblLoading, lblLoadingIcon;
  private double version = 1.3;
  private JTabbedPane pane;

  public MainFrame()
          throws HeadlessException {
    try {
      for (UIManager.LookAndFeelInfo info : UIManager.getInstalledLookAndFeels()) {
        if ("Nimbus".equals(info.getName())) {
          UIManager.setLookAndFeel(info.getClassName());
          break;
        }
      }
    } catch (Exception e) {
    }

    setDefaultCloseOperation(3);
    setSize(800, 600);
    setCenter();    

    this.pnlMain = new JPanel(new BorderLayout());
    loadNewspapers();
    setContentPane(this.pnlMain);
    setIcon();
    setTitle("ورزش ۳ نسخه " + version);
    initComponents();
    setVisible(true);

    checkUpdate();
  }

  private void setCenter() {
    Dimension dimension = Toolkit.getDefaultToolkit().getScreenSize();
    int x = (int) ((dimension.getWidth() - getWidth()) / 2.0D);
    int y = (int) ((dimension.getHeight() - getHeight()) / 2.0D);
    setLocation(x, y);
  }

  private void loadNewspapers() {
    JPanel pnlLoading = new JPanel(new BorderLayout());
    pnlLoading.setBackground(Color.WHITE);
    ImageIcon progress = new ImageIcon(RL.class.getResource("loader.gif"));
    lblLoadingIcon = new JLabel(progress, JLabel.CENTER);
    lblLoading = new JLabel("LOADING ...", JLabel.CENTER);
    Font font = lblLoading.getFont();
    //font = new Font(font.getFontName(), font.getStyle(), 16);
    lblLoading.setFont(font);
    pnlLoading.add(lblLoadingIcon, BorderLayout.CENTER);
    pnlLoading.add(lblLoading, BorderLayout.SOUTH);
    this.pnlMain.add(pnlLoading, "Center");

    this.fetcher = new NewspaperFetch();
    Thread t = new Thread(this.fetcher);
    this.fetcher.addObserver(this);
    t.start();
  }

  public void update(Observable o, Object arg) {
    if ((arg instanceof ArrayList)) {
      this.newspapers = ((ArrayList) arg);
      boolean allLoaded = true;
      do {
        allLoaded = true;
        for (Newspaper newspaper : this.newspapers) {
          if (!newspaper.loaded()) {
            allLoaded = false;
            break;
          }
        }
      } while (!allLoaded);

      showNewspapers();
    } else if ((arg instanceof Exception)) {
      Exception ex = (Exception) arg;
      JOptionPane.showMessageDialog(this, new StringBuilder().append("Error").append(ex.getMessage()).toString(), "Error", 0);
    }
  }

  private void showNewspapers() {
    pane = new JTabbedPane();

    for (Newspaper newspaper : this.newspapers) {
      ImageIcon icon = new ImageIcon(newspaper.getImg());
      JLabel lblN = new JLabel(icon);
      JPanel pnl = new JPanel(new BorderLayout());
      pnl.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);
      pnl.add(lblN, "Center");
      pane.addTab(newspaper.getTitle(), pnl);
    }

    this.pnlMain.removeAll();
    this.pnlMain.add(pane, "Center");
    this.pnlMain.setVisible(false);
    this.pnlMain.invalidate();
    this.pnlMain.repaint();
    this.pnlMain.setVisible(true);
    pane.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);
    displayRanking();
  }

  public static void main(String[] args) {
    MainFrame mainFrame = new MainFrame();
  }

  private void setIcon() {
    Image icon = new ImageIcon(RL.class.getResource("icon.png")).getImage();
    setIconImage(icon);
  }

  private void checkUpdate() {
    try {
      Updater updater = new Updater("http://ehsunbehravesh.com/varzesh3/version", "http://ehsunbehravesh.com/varzesh3/Varzesh3.jar", "http://ehsunbehravesh.com/varzesh3/hash", version);
      File file = new File(Utils.getPathOfJar(true) + "/Varzesh3.jar");
      updater.setExistingFile(file);
      updater.addObserver(new Observer() {
        @Override
        public void update(Observable o, Object arg) {

          System.out.println("Updater: " + arg.toString());
          if (arg instanceof String && (arg.toString().equals(Updater.OLD_FILE_DELETE_FAILED) || 
                  arg.toString().equals(Updater.NEW_FILE_RENAME_FAILED))) {
            showManualUpdateMessage(((Updater)o).getNewVersion());
          }

        }
      });

      new Thread(updater).start();
    } catch (MalformedURLException ex) {
      Logger.getLogger(MainFrame.class.getName()).log(Level.SEVERE, null, ex);
    }
  }
  
  private void showManualUpdateMessage(double newVersion) {
    JOptionPane.showMessageDialog(this, "نسخه جدیدی از برنامه دانلود شده است.\n لطفا به مسیر برنامه رفته و فایل Varzesh3.jar را حذف کرده و فایل Varzesh3-" + newVersion + " را به Varzesh3.jar تغییر نام دهید.", "نسخه جدید", JOptionPane.WARNING_MESSAGE);
  }

  private void displayRanking() {
    RankingFetch fetcher = new RankingFetch();
    fetcher.addObserver(new Observer() {
      @Override
      public void update(Observable o, Object arg) {
        if (arg instanceof Ranking) {
          JPanel pnlRankingTable = new JPanel(new BorderLayout());
          pnlRankingTable.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);
          JTable jTable = new JTable(new RankingTableModel((Ranking) arg));      
          jTable.setFont(new Font("Tahoma", Font.PLAIN, jTable.getFont().getSize()));
          jTable.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);
          JScrollPane scpTable = new JScrollPane(jTable);
          scpTable.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);
          pnlRankingTable.add(scpTable, BorderLayout.CENTER);
          pane.add("جدول لیگ برتر فوتبال", pnlRankingTable);
        }
      }
    });
    new Thread(fetcher).start();
  }

  private void initComponents() {
    setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);
    setFont(new Font("Tahoma", Font.PLAIN, 12));
    pnlMain.setFont(new Font("Tahoma", Font.PLAIN, 12));
    pnlMain.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);
  }
}